﻿using System;
using System.IO;

namespace K9Nano.Storage
{
    /// <summary>
    /// 安全的使用临时文件
    /// <example>示例：
    /// <code>
    /// using (var tmp = new SafeTmpFile())
    /// {
    /// } // 临时文件将被删除
    /// </code>
    /// </example>
    /// </summary>
    public sealed class SafeTmpFile : IDisposable
    {
        private readonly string _file;

        public string File
        {
            get
            {
                if(_disposed) throw new ObjectDisposedException(nameof(SafeTmpFile));
                return _file;
            }
        }

        public SafeTmpFile()
        {
            _file = Path.GetTempFileName();
        }

        public Stream Open() => System.IO.File.Open(_file, FileMode.OpenOrCreate, FileAccess.ReadWrite);

        private bool _disposed = false;

        public void Dispose()
        {
            if (System.IO.File.Exists(_file))
            {
                System.IO.File.Delete(_file);
            }

            _disposed = true;
        }

        ~SafeTmpFile()
        {
            Dispose();
        }
    }
}